package com.heima.behavior.service.impl;

import com.heima.behavior.dto.UnLikesBehaviorDto;
import com.heima.behavior.entity.ApUnlikesBehavior;
import com.heima.behavior.service.IApUnlikesBehaviorService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.MediaThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.net.DatagramSocket;
import java.util.Date;

@Service
public class ApUnlikesBehaviorServiceImpl implements IApUnlikesBehaviorService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 文章不喜欢行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveUnlikes(UnLikesBehaviorDto dto) {
        //获取当前登录用户
        User user = MediaThreadLocalUtil.get();
        //创建不喜欢用户表
        ApUnlikesBehavior apUnlikesBehavior=new ApUnlikesBehavior();
        apUnlikesBehavior.setEquipmentId(dto.getEquipmentId());
        //如果登录
        if (user!=null){
            apUnlikesBehavior.setUserId(user.getUserId());
        }
        apUnlikesBehavior.setArticleId(dto.getArticleId());
        apUnlikesBehavior.setType(dto.getType());
        apUnlikesBehavior.setCreatedTime(new Date());
        //查询是否文章不喜欢是否存在
        Query query=new Query();
        if (user!=null) {
            query.addCriteria(Criteria.where("userId").is(dto.getUserId()));
        }else {
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));

        ApUnlikesBehavior one = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        //如果不存在,新增
        if (one==null){
            mongoTemplate.save(apUnlikesBehavior);
        }else {
            //如果存在,删除
            if (one.getType() !=dto.getType()){
                one.setType(dto.getType());
                mongoTemplate.save(one);
            }
        }
        return ResponseResult.okResult();
    }

    /**
     * 不喜欢行为表查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult<ApUnlikesBehavior> getUnlikes(UnLikesBehaviorDto dto) {
        Query query=new Query();
        query.addCriteria(Criteria.where("articleId").is(dto.getArticleId()));
        if (dto.getUserId()==null){
            query.addCriteria(Criteria.where("equipmentId").is(dto.getEquipmentId()));
        }else {
            query.addCriteria(Criteria.where("userId").is(dto.getUserId()));
        }
        ApUnlikesBehavior one = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
        return ResponseResult.okResult(one);
    }
}
